package br.com.bringme.mvc;

import java.lang.reflect.Method;

public abstract class Controller {
	
	protected Params params = new Params();
	protected View view = new View() {
		private static final long serialVersionUID = 604210219457692488L;
	};
	
	public Controller() {
		init();
	}
	
	public void indexAction() {
		
	}
	
	public abstract void init();
	
	public Params getParams() {
		return params;
	}
	
	public void setParam(String chave, Object valor) {
		getParams().set(chave, valor);
	}
	
	public <T> T getParam(String chave, T valorPadrao) {
		return (T) getParams().get(chave, valorPadrao);
	}
	
	@SuppressWarnings("unchecked")
	public <T> T getParam(String chave) {
		return (T) getParams().get(chave);
	}
	
	public View getView() {
		return view;
	}
	
	public void dispatch(String action) {
		dispatch(action, getParams());
	}
	
	public void dispatch(String action, Params params) {
		
		Method method;
		try {
			method = getClass().getMethod(action.toLowerCase().concat("Action"));
			method.invoke(this);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public static void dispatch(Class<Controller> clazz, String action) {
		Controller c = Singleton.getInstance(clazz);
		c.dispatch(action);
	}
	
	public static void dispatch(Class<Controller> clazz, String action, Params params) {
		Controller c = Singleton.getInstance(clazz);
		c.dispatch(action, params);
		
	}

}
